<template>
    <div class="proctor-task-dashboard">
      <el-row :gutter="20" class="top-row" justify="space-between">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-title">本月监考统计</div>
            <div class="stat-value main-number">{{ totalCount }}</div>
            <div class="stat-desc">总场次</div>
            <div ref="barChartRef" class="echarts-box"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-title">教师平均监考工作量</div>
            <div class="stat-value main-number">{{ avgCount }}</div>
            <div class="stat-desc">次/人</div>
            <div ref="pieChartRef" class="echarts-box"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-title">工作量预警</div>
            <div class="stat-value main-number warning">{{ overLimitCount }}</div>
            <div class="stat-desc warning">超额教师数</div>
            <div class="stat-alert"><el-icon style="color:#f56c6c;margin-right:4px;"><WarningFilled /></el-icon><span class="warning">有{{ overLimitCount }}位教师监考次数超过规定</span></div>
          </el-card>
        </el-col>
      </el-row>
      <div class="bottom-flex-row">
        <el-card class="teacher-list-card">
          <div class="teacher-list-header">
            <el-input v-model="teacherFilter" placeholder="搜索教师名/工号" clearable size="small" />
          </div>
          <el-scrollbar class="teacher-list-scroll">
            <div v-for="t in filteredTeachers" :key="t.teacherId" class="teacher-item">
              <el-avatar class="teacher-avatar" :size="48" style="background:#dbeafe;color:#409eff;">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="teacher-name">{{ t.teacherName }}</span>
              <span class="teacher-count">{{ t.count }}次</span>
            </div>
          </el-scrollbar>
        </el-card>
        <el-card class="task-detail-card">
          <div class="task-detail-header">
            <span>监考任务详情</span>
            <el-select v-model="taskFilter" placeholder="筛选教师" size="small" style="width: 180px; margin-left: 16px;">
              <el-option v-for="t in teacherList" :key="t.teacherId" :label="t.teacherName" :value="t.teacherId" />
            </el-select>
            <el-button type="primary" size="small" style="margin-left: 8px;" @click="confirmTask">确认监考</el-button>
            <el-button size="small" style="margin-left: 8px;" @click="openAppealDialog">提交申诉</el-button>
          </div>
          <el-table
            :data="filteredTasksByPage"
            row-key="taskId"
            highlight-current-row
            :current-row="taskDetail"
            @row-click="handleRowClick"
            style="width: 100%; margin-top: 10px;"
            stripe
          >
            <el-table-column prop="examName" label="考试名称" min-width="160" />
            <el-table-column prop="examDate" label="时间" min-width="120">
              <template #default="{ row }">
                {{ formatDate(row.examDate) }} {{ row.startTime }}-{{ row.endTime }}
              </template>
            </el-table-column>
            <el-table-column prop="classroomName" label="地点" min-width="120" />
            <el-table-column prop="taskStatus" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.taskStatus)" effect="light">
                  <el-icon v-if="statusTagIcon(row.taskStatus)" style="margin-right:4px;">
                    <component :is="statusTagIcon(row.taskStatus)" />
                  </el-icon>
                  {{ statusMap[row.taskStatus] || row.taskStatus }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-if="filteredTasks.length > pageSize"
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="filteredTasks.length"
            layout="prev, pager, next"
            style="margin: 16px 0 0; text-align: right;"
          />
          <div v-if="taskDetail" class="task-detail-flex">
            <div class="task-detail-left">
              <div class="detail-title">考试信息</div>
              <div>考试名称：{{ taskDetail.examName }}</div>
              <div>时间：{{ formatDate(taskDetail.examDate) }} {{ taskDetail.startTime }}-{{ taskDetail.endTime }}</div>
              <div>地点：{{ taskDetail.classroomName }}</div>
            </div>
            <div class="task-detail-right">
              <div class="detail-title">监考信息</div>
              <div>教师：{{ taskDetail.teacherName }}</div>
              <div>角色：{{ taskDetail.role }}</div>
            </div>
          </div>
        </el-card>
      </div>
      <el-dialog v-model="appealDialogVisible" title="申诉理由" width="400px">
        <el-input v-model="appealContent" type="textarea" :rows="4" placeholder="请填写申诉理由" />
        <template #footer>
          <el-button @click="appealDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppeal">提交</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted, nextTick, watch, defineEmits } from 'vue'
  import * as echarts from 'echarts'
  import { ElMessage } from 'element-plus'
  import axios from 'axios'
  import { WarningFilled, User, Check, InfoFilled, CloseBold, Clock } from '@element-plus/icons-vue'
  
  const teacherList = ref([])
  const totalCount = ref(0)
  const avgCount = ref(0)
  const overLimitCount = ref(0)
  const taskList = ref([])
  
  const fetchStats = async () => {
    try {
      const { data } = await axios.get('/api/proctor/task/stats')
      const stats = data.data || {}
      teacherList.value = stats.list || []
      totalCount.value = stats.total || 0
      avgCount.value = stats.avg || 0
      overLimitCount.value = stats.overLimitCount || 0
      renderCharts()
    } catch (e) {
      ElMessage.error('获取监考统计失败')
    }
  }
  
  const fetchTasksByTeacher = async (teacherId) => {
    if (!teacherId) { taskList.value = []; return }
    try {
      const { data } = await axios.get(`/api/proctor/task/teacher/${teacherId}`)
      taskList.value = data.data || []
    } catch (e) {
      ElMessage.error('获取监考任务失败')
      taskList.value = []
    }
  }
  
  const teacherFilter = ref('')
  const filteredTeachers = computed(() =>
    teacherList.value.filter(t =>
      !teacherFilter.value || t.teacherName.includes(teacherFilter.value)
    )
  )
  
  const taskFilter = ref('')
  
  // 只要 taskFilter 变化就拉取数据
  watch(taskFilter, (val) => {
    if (val) fetchTasksByTeacher(val)
  })
  
  // teacherList变化时，始终选中第一个教师，无则清空
  watch(teacherList, (list) => {
    if (list.length > 0) {
      taskFilter.value = list[0].teacherId
    } else {
      taskFilter.value = ''
      taskList.value = []
    }
  })
  
  // 直接展示 taskList
  const filteredTasks = computed(() => taskList.value)
  
  // 1. 分页相关变量
  const pageSize = ref(4)
  const currentPage = ref(1)
  const filteredTasksByPage = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return filteredTasks.value.slice(start, start + pageSize.value)
  })
  
  const barChartRef = ref()
  const pieChartRef = ref()
  
  const renderCharts = () => {
    nextTick(() => {
      // 柱状图
      if (barChartRef.value) {
        const barChart = echarts.init(barChartRef.value)
        barChart.setOption({
          xAxis: { type: 'category', data: teacherList.value.map(t => t.teacherName) },
          yAxis: { type: 'value' },
          series: [{ type: 'bar', data: teacherList.value.map(t => t.count), itemStyle: { color: '#409eff' } }],
          grid: { left: 30, right: 10, top: 20, bottom: 20 }
        })
      }
      // 环形图
      if (pieChartRef.value) {
        const pieChart = echarts.init(pieChartRef.value)
        pieChart.setOption({
          series: [{
            type: 'pie',
            radius: ['60%', '80%'],
            avoidLabelOverlap: false,
            label: { show: false },
            data: [
              { value: Number(avgCount.value), name: '平均' },
              { value: Math.max(totalCount.value - Number(avgCount.value), 0), name: '其他', itemStyle: { color: '#f5f6fa' } }
            ],
            color: ['#409eff', '#f5f6fa']
          }]
        })
      }
    })
  }
  
  const statusMap = {
    PENDING_CONFIRM: '待确认',
    CONFIRMED: '已确认',
    APPEALED: '已申诉',
    REJECTED: '已驳回'
  }
  const statusTagType = status => {
    switch (status) {
      case 'CONFIRMED': return 'success'
      case 'PENDING_CONFIRM': return 'warning'
      case 'APPEALED': return 'info'
      case 'REJECTED': return 'danger'
      default: return ''
    }
  }
  const statusTagIcon = status => {
    switch (status) {
      case 'CONFIRMED': return Check
      case 'PENDING_CONFIRM': return Clock
      case 'APPEALED': return InfoFilled
      case 'REJECTED': return CloseBold
      default: return null
    }
  }
  const formatDate = d => d
  
  const taskDetail = ref(null)
  
  const handleRowClick = (row) => {
    taskDetail.value = row
  }
  
  // 4. 页码变化时自动高亮第一页第一条
  watch([filteredTasks, currentPage], ([tasks, page]) => {
    if (tasks.length > 0) {
      const pageTasks = filteredTasksByPage.value
      if (pageTasks.length > 0) {
        nextTick(() => handleRowClick(pageTasks[0]))
      } else {
        taskDetail.value = null
      }
    } else {
      taskDetail.value = null
    }
  }, { immediate: true })
  
  // 申诉弹窗相关
  const appealDialogVisible = ref(false)
  const appealContent = ref('')
  const currentTask = ref(null)
  
  const openAppealDialog = () => {
    if (!taskDetail.value || !taskDetail.value.taskId) {
      ElMessage.warning('请先选择监考任务')
      return
    }
    currentTask.value = taskDetail.value
    appealContent.value = ''
    appealDialogVisible.value = true
  }
  
  const submitAppeal = async () => {
    if (!appealContent.value.trim()) {
      ElMessage.warning('请填写申诉理由')
      return
    }
    try {
      await axios.put('/api/proctor/task/appeal', {
        taskId: currentTask.value.taskId,
        appealContent: appealContent.value,
        taskStatus: 'APPEALED'
      })
      ElMessage.success('申诉已提交')
      appealDialogVisible.value = false
      fetchTasksByTeacher(taskFilter.value)
    } catch (e) {
      ElMessage.error('申诉提交失败')
    }
  }
  
  const emit = defineEmits(['refreshExamList'])
  
  const confirmTask = async () => {
    if (!taskDetail.value || !taskDetail.value.taskId) {
      ElMessage.warning('请先选择监考任务')
      return
    }
    try {
      await axios.put(`/api/proctor/task/confirm/${taskDetail.value.taskId}`)
      ElMessage.success('已确认监考')
      fetchTasksByTeacher(taskFilter.value)
      emit('refreshExamList')
    } catch (e) {
      ElMessage.error('确认失败')
    }
  }
  
  onMounted(() => {
    fetchStats()
    // 默认选中第一个老师，加载其任务
    watch(
      () => filteredTeachers.value,
      (list) => {
        if (list.length > 0) {
          taskFilter.value = list[0].teacherId
        }
      },
      { immediate: true }
    )
  })
  </script>
  
  <style scoped>
  .proctor-task-dashboard {
    padding: 24px 32px;
    min-width: 100%;
    background: #f5f6fa;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .top-row {
    flex-shrink: 0;
    margin-bottom: 20px;
  }
  .top-row .el-col {
    display: flex;
  }
  .stat-card {
    flex: 1 1 0;
    min-width: 0;
    min-height: 240px;
    height: auto;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    box-sizing: border-box;
    position: relative;
  }
  .stat-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .stat-value.main-number {
    font-size: 48px;
    font-weight: bold;
    margin-bottom: 4px;
    text-align: left;
  }
  .stat-desc {
    font-size: 16px;
    color: #888;
    margin-bottom: 8px;
    text-align: left;
  }
  .stat-alert {
    margin-top: 8px;
    font-size: 14px;
    color: #f56c6c;
    display: flex;
    align-items: center;
  }
  /* 图表容器右下角固定并放大 */
  .stat-card > div[ref], .stat-card .echarts-box {
    position: absolute;
    right: 16px;
    bottom: 16px;
    max-width: 80%;
    max-height: 80%;
    min-width: 120px;
    min-height: 120px;
    width: auto;
    height: auto;
  }
  /* 让柱状图和环形图都用这个类 */
  .bottom-flex-row {
    display: flex;
    flex: 1;
    min-height: 0;
    gap: 20px;
    margin-top: 20px;
    align-items: stretch;
  }
  .teacher-list-card, .task-detail-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
  }
  .teacher-list-card {
    flex: 0 0 260px;
    min-width: 220px;
    max-width: 320px;
  }
  .task-detail-card {
    flex: 1;
    min-width: 0;
  }
  .teacher-list-header {
    margin-bottom: 10px;
  }
  .teacher-list-scroll {
    flex: 1;
    min-height: 0;
  }
  .teacher-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  .teacher-avatar {
    margin-right: 10px;
    background: #dbeafe;
    color: #409eff;
  }
  .teacher-name {
    margin-left: 0;
    flex: 1;
  }
  .teacher-count {
    color: #409eff;
    font-weight: bold;
    margin-left: 8px;
  }
  .task-detail-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
  .el-table {
    flex: 1;
    min-height: 0;
  }
  .warning {
    color: #f56c6c !important;
  }
  .task-detail-flex {
    display: flex;
    flex-direction: row;
    gap: 40px;
    margin-top: 24px;
  }
  .task-detail-left, .task-detail-right {
    flex: 1;
    min-width: 0;
  }
  .detail-title {
    font-weight: bold;
    margin-bottom: 8px;
  }
  </style> 